//
//  WYShareController.m
//  Boss
//
//  Created by admin on 2018/6/29.
//  Copyright © 2018年 admin. All rights reserved.
//
#import "WYRuleController.h"
#import "WYShareController.h"
#import "WXApi.h"
//#import <NSData+YYAdd.h>
#import "WeiboSDK.h"
//#import  <TencentOpenAPI/QQApi.h>
#import <TencentOpenAPI/QQApiInterface.h>

#import <Photos/Photos.h>

@interface WYShareController ()
@property (strong, nonatomic) IBOutlet UIImageView *backgroundImage;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *bottomHeight;

@property (nonatomic,strong)NSString *template;
@property (nonatomic,strong)NSString *qrCode;

@property (strong, nonatomic) IBOutlet NSLayoutConstraint *templateImageViewWidth;
@property (strong, nonatomic) IBOutlet UIScrollView *scrollView;
@property (strong, nonatomic) IBOutlet UIView *mainView;

@property (strong, nonatomic) IBOutlet NSLayoutConstraint *userImageViewTopHeight;

@property (strong, nonatomic) IBOutlet UIImageView *userImageView;
@property (strong, nonatomic) IBOutlet UILabel *userName;

@property (strong, nonatomic) IBOutlet UIImageView *QRImageView;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *userImageViewWidth;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *userImageViewHeight;

@property (strong, nonatomic) IBOutlet UIButton *saveBtn;
@property (strong, nonatomic) IBOutlet UIButton *shareBtn;

@property (strong, nonatomic) IBOutlet UIView *bottomView;

@property (strong, nonatomic) IBOutlet UIView *shareBottomView;
@property (strong, nonatomic) IBOutlet UIView *transformView;

@property (strong, nonatomic) IBOutlet NSLayoutConstraint *backImageViewWidth;


@end

@implementation WYShareController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadData];
    self.bottomHeight.constant = 44;
   // [self wr_setNavBarBackgroundAlpha:0];
    //self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"保存到相册" style:(UIBarButtonItemStyleDone) target:self action:@selector(saveImagetoLibary)];
    self.navigationItem.title = @"邀请好友";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"Tips_icon"] style:(UIBarButtonItemStyleDone) target:self action:@selector(tipsAction:)];
    self.backgroundImage.contentMode = UIViewContentModeScaleAspectFill;
    self.backImageViewWidth.constant = kScreenWidth;
    [self.scrollView addSubview:self.mainView];
    self.mainView.width = kScreenWidth;
    self.userImageViewWidth.constant = 85*kScreenWidth/750.f;
    self.userImageViewHeight.constant = 85*kScreenWidth/750.f;
    
    [self.userImageView setCornerRadius:self.userImageViewHeight.constant/2.0f];
    WYUserMessage *userMessage = [WYStoreModule currentUserMessage];
    
    [self.userImageView sd_setImageWithURL:[NSURL URLWithString:userMessage.url] placeholderImage:nil];
    self.userName.text = userMessage.userName;
    
    [self.saveBtn setBorderWithWidth:1 andColor:[UIColor whiteColor]];
    [self.saveBtn setCornerRadius:25.f];
    [self.shareBtn setCornerRadius:25.f];
    
    
                                                                                                                                                                                                                                                                                                                                        
    
    
    
    // Do any additional setup after loading the view from its nib.
}
-(void)tipsAction:(UIBarButtonItem *)item
{
    WYRuleController *rvc = [[WYRuleController alloc]init];
    [self.navigationController pushViewController:rvc animated:YES];
}
- (IBAction)saveAction:(id)sender {
    [self saveImagetoLibary];
}
- (IBAction)shareAction:(id)sender {
    
    self.transformView.transform = CGAffineTransformMakeScale(1.0f, 1.0f);//将要显示的view按照正常比例显示出来
    self.userImageViewTopHeight.constant = self.templateImageViewWidth.constant *874/1336;
    [UIView beginAnimations:nil context:UIGraphicsGetCurrentContext()];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];  //InOut 表示进入和出去时都启动动画
    [UIView setAnimationDuration:0.5f];//动画时间
    self.transformView.transform=CGAffineTransformMakeScale(0.8f, 0.8f);//先让要显示的view最小直至消失
    [UIView commitAnimations]; //启动动画
    self.shareBottomView.hidden = NO;
    self.bottomView.hidden = YES;
    
}


-(void)saveImagetoLibary
{
    
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusRestricted) { // 此应用程序没有被授权访问的照片数据。可能是家长控制权限。
        NSLog(@"因为系统原因, 无法访问相册");
    } else if (status == PHAuthorizationStatusDenied) { // 用户拒绝访问相册
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"警告" message:@"请去-> [设置 - 隐私 - 相机 - 项目名称] 打开访问开关" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去设置", nil];
        [alertView show];
    } else if (status == PHAuthorizationStatusAuthorized) { // 用户允许访问相册
         UIImageWriteToSavedPhotosAlbum([self convertViewToImage:self.transformView], self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
        
        // 放一些使用相册的代码
    } else if (status == PHAuthorizationStatusNotDetermined) { // 用户还没有做出选择
        // 弹框请求用户授权
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if (status == PHAuthorizationStatusAuthorized) { // 用户点击了好
                // 放一些使用相册的代码
            }
        }];
    }
    
    
    
    
    
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (!error) {
        [self toast:@"保存成功"];
    }
    NSLog(@"image = %@, error = %@, contextInfo = %@", image, error, contextInfo);
}



-(void)loadData
{
    WYUserMessage *userMessage = [WYStoreModule currentUserMessage];
    WEAKSELF
    [WYHttpServer getShareBackgroundWithPhone:userMessage.phone SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            weakSelf.template = response[@"result"][@"template"];
            weakSelf.qrCode = response[@"result"][@"qrCode"];
            [weakSelf reloadImageView];
        }
    }];
    
    
}

-(void)reloadImageView
{
    WEAKSELF
    [self.backgroundImage sd_setImageWithURL:[NSURL URLWithString:self.template] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        weakSelf.templateImageViewWidth.constant = kScreenWidth/(image.size.width/image.size.height);
        weakSelf.mainView.width = kScreenWidth;
        weakSelf.mainView.height = weakSelf.templateImageViewWidth.constant+80;
        [weakSelf.scrollView setContentSize:weakSelf.mainView.size];
        weakSelf.userImageViewTopHeight.constant = weakSelf.templateImageViewWidth.constant *874/1336;
        
        
        
//
//        weakSelf.bottomView.frame = CGRectMake(0, weakSelf.templateImageViewWidth.constant, kScreenWidth, 70);
//        [weakSelf.scrollView addSubview:weakSelf.bottomView];
//
//        weakSelf.shareBottomView.frame = CGRectMake(0, weakSelf.templateImageViewWidth.constant, kScreenWidth, 70);
//        [weakSelf.scrollView addSubview:weakSelf.shareBottomView];
//
//        weakSelf.shareBottomView.hidden = YES;
        
        
    }];
    
    [weakSelf.QRImageView sd_setImageWithURL:[NSURL URLWithString:self.qrCode] placeholderImage:nil];
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)wechatShareAction:(id)sender {
    WXMediaMessage *message = [WXMediaMessage message];
   // [message setThumbImage:self.backgroundImage.image];
    WXImageObject *imageObject = [WXImageObject object];
    UIImage *image = [self convertViewToImage:self.transformView];
    NSData *data = UIImagePNGRepresentation(image);
    imageObject.imageData = data;
    // 多媒体数据对象，可以为WXImageObject，WXMusicObject，WXVideoObject，WXWebpageObject等。
    message.mediaObject = imageObject;
    
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    req.scene = WXSceneSession;// 分享到朋友圈
    [WXApi sendReq:req];
}

- (IBAction)firendAction:(id)sender {
    
    WXMediaMessage *message = [WXMediaMessage message];
    //[message setThumbImage:[UIImage imageNamed:@"example"]];
    WXImageObject *imageObject = [WXImageObject object];
    UIImage *image = [self convertViewToImage:self.transformView];
    NSData *data = UIImagePNGRepresentation(image);
    imageObject.imageData = data;
    // 多媒体数据对象，可以为WXImageObject，WXMusicObject，WXVideoObject，WXWebpageObject等。
    message.mediaObject = imageObject;
    
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    req.scene = WXSceneTimeline;// 分享到朋友圈
    [WXApi sendReq:req];
    
    
    
    
}

-(UIImage*)convertViewToImage:(UIView*)v{
    CGSize s = v.bounds.size;
    
    
    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(s.width, s.height+20), NO, [UIScreen mainScreen].scale);
    [v.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

- (IBAction)QQShare:(id)sender {
    
//    QQApiImageObject *imgObj = [QQApiImageObject objectWithData:imgData previewImageData:previewImage title:self.newsModel.title description:@"由 桂林理工大学-校园通 转码"];
    NSData *data = UIImagePNGRepresentation([self convertViewToImage:self.transformView]);
    
    
   QQApiImageObject *imgObj = [QQApiImageObject objectWithData:data previewImageData:data title:@"123" description:@"123"];
    
    
    SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:imgObj];
    
    //将内容分享到qq
    
    QQApiSendResultCode sent = [QQApiInterface sendReq:req];
    
}
- (IBAction)QQZone:(id)sender {
    
    NSData *data = UIImagePNGRepresentation([self convertViewToImage:self.transformView]);
    
    
    QQApiImageObject *imgObj = [QQApiImageObject objectWithData:data previewImageData:data title:@"123" description:@"123"];
    
    
    SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:imgObj];
    
    //将内容分享到qq
    
    QQApiSendResultCode sent = [QQApiInterface SendReqToQZone:req];
    
    
    
}
- (IBAction)weiboShare:(id)sender {
    [WeiboSDK shareToWeibo:@"123"];
    
    
    
}


@end
